import requests
from lxml import etree

class Ksw:
    "00ksw.org 操作类"

    # 以get方式请求网页
    def request(url):
        try:
            req = requests.get(url)
            req.encoding = "gbk"
            return req.text
        except:
            return ""

    # 获取小说所有章节
    def getlist(url):
        ele = etree.HTML(Ksw.request(url))
        a = ele.xpath('//*[@id="list"]/dl/dd/a')

        href = []
        for x in a:
            href.append("%s/%s" % (url, x.attrib["href"]))

        return href

    # 获取小说内容
    def getcontent(url):
        ele     = etree.HTML(Ksw.request(url))
        title   = ele.xpath('//*[@class="bookname"]/h1')
        content = ele.xpath('//*[@id="content"]/text()')

        return {
            "title"   : title[0].text,
            "content" : Ksw.format("\r\n".join(content))
        }

    # 格式化小说内容
    def format(content):
        return content.replace('www.lingdiankanshu.com', '')

